package com.tanhua.server.serivce;

import com.tanhua.domain.db.*;
import com.tanhua.domain.mongo.SoulReport;
import com.tanhua.domain.mongo.SoulResult;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.api.mongo.SoulReportApi;
import com.tanhua.dubbo.api.mongo.SoulResultApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TestSoulService {
    @Reference
    private TestSoulApi testSoulApi;

    @Reference
    private SoulQuestionsApi soulQuestionsApi;
    @Reference
    private SoulOptionsApi soulOptionsApi;
    @Reference
    private SoulLockApi soulLockApi;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Reference
    private SoulReportApi soulReportApi;
    @Reference
    private SoulResultApi soulResultApi;
    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 接口名称：测灵魂-问卷列表
     * 接口路径：GET/testSoul
     */
    public ResponseEntity<Object> soulQuestionnaire() {
        Long userId = UserHolder.getUserId();

        List<SoulQuestionnaire> soulQuestionnaireList = testSoulApi.findSoulQuestionnaire();

        List<QuestionnaireVo> questionnaireVoList = new ArrayList<>();

        if (soulQuestionnaireList != null){
                for (SoulQuestionnaire soulQuestionnaire : soulQuestionnaireList) {
                    QuestionnaireVo questionnaireVo = new QuestionnaireVo();
                    questionnaireVo.setId(soulQuestionnaire.getId().toString());
                    BeanUtils.copyProperties(soulQuestionnaire,questionnaireVo);

                //调用api查找 question 对应的试题
                List<SoulQuestions> soulQuestionList = soulQuestionsApi.findSoulQuestionList(questionnaireVo.getLevel());
                List<QuestionsVo> questionsVoList = new ArrayList<>();
                if (soulQuestionList != null) {
                    for (SoulQuestions soulQuestions : soulQuestionList) {
                        QuestionsVo questionsVo = new QuestionsVo();
                        BeanUtils.copyProperties(soulQuestions,questionsVo);
                        questionsVo.setId(soulQuestions.getQuestionId());



                        //调用api 通过level和题号 获取所有选项
                        List<SoulOptions> optionsList = soulOptionsApi.findSoulOptionsList(soulQuestions.getQuestionId()) ;
                        List<OptionsVo> optionsVoList = new ArrayList<>();
                        if (optionsList != null) {
                            for (SoulOptions soulOptions : optionsList) {
                                OptionsVo optionsVo = new OptionsVo();
                                optionsVo.setId(soulOptions.getOptionId());
                                optionsVo.setOption(soulOptions.getOption());
                                //把选项对象添加到对应的list中
                                optionsVoList.add(optionsVo);
                            }
                        }
                        //将得到的对应的选项加到试题中
                        questionsVo.setOptions(optionsVoList);
                        //将试题添加到对应的 试题list中
                        questionsVoList.add(questionsVo);
                    }
                }

                //将每一套题 加到要返回的list对象中
                questionnaireVo.setQuestions(questionsVoList);

                //调用api查询试题是否解锁
                Integer isLock = soulLockApi.findIsLock(userId,soulQuestionnaire.getLevel());
                questionnaireVo.setIsLock(isLock);

                //通过level和userId 在Lock表中查询report Id
                Long reportId =  soulLockApi.findReportId(userId,soulQuestionnaire.getLevel());
                if (reportId != null) {
                    questionnaireVo.setReportId(reportId.toString());
                }

                questionnaireVoList.add(questionnaireVo);

            }
        }

        return ResponseEntity.ok(questionnaireVoList);
    }

    /**
     * 接口名称：测灵魂-提交问卷
     * 接口路径：POST/testSoul
     */
    public ResponseEntity<Object> giveSoulQuestionnaire(List<AnswersVo> answers) {
        // 通过每个answers中的questionId和optionId得到每道题的得分，然后得到总分
        Integer totalScore = 0;
        Integer countA = 0;
        Integer countB = 0;
        Integer countC = 0;
        Integer countDEFG = 0;
        for (AnswersVo answer : answers) {
            String questionId = answer.getQuestionId();
            String optionId = answer.getOptionId();
            Integer score = soulOptionsApi.findScore(questionId,optionId);
            totalScore += score;
            switch (optionId){
                case "A":
                    countA += 1;
                    break;
                case "B":
                    countB += 1;
                    break;
                case "C":
                    countC += 1;
                    break;
                case "D":
                    countDEFG += 1;
                    break;
                case "E":
                    countDEFG += 1;
                    break;
                case "F":
                    countDEFG += 1;
                    break;
                case "G":
                    countDEFG += 1;
                    break;

            }
        }
        SoulReport soulReport = new SoulReport();
        // 得到resultId

        Random random = new Random();
        soulReport.setAbstract1(20 + (random.nextInt(10) + countA * 7));
        soulReport.setJudgment(20 + (random.nextInt(10) + countB * 7));
        soulReport.setOutgoing(20 + (random.nextInt(10) + countC * 7));
        soulReport.setRationality(20 + (random.nextInt(10) + countDEFG * 7));

        if (totalScore < 21) {
            soulReport.setResultId(1);

        } else if ( 21 <= totalScore && totalScore <= 40){
            soulReport.setResultId(2);

        } else if ( 41 <= totalScore && totalScore <= 55){
            soulReport.setResultId(3);

        } else {
            soulReport.setResultId(4);

        }
        soulReport.setUserId(UserHolder.getUserId());

        String questionId = answers.get(0).getQuestionId();
        String level =  soulQuestionsApi.getLevel(questionId);
        soulReport.setLevel(level);
        // 实现reportId自增长 并将结果写进mongo表
        Long reportId = soulReportApi.save(soulReport);
        Long userId = UserHolder.getUserId();
        //将reportId 存入lock表
        soulLockApi.saveReportId(userId,level,reportId);

        //解锁下一个级别
        soulLockApi.updateIsLock(userId,level);

        return ResponseEntity.ok(reportId.toString());
    }

    //查看结果
    public ResponseEntity<Object> showReport(String reportId) {
        //根据reportId 去查询结果对象
        SoulReport soulReport = soulReportApi.findByReportId(reportId);
        SoulResult soulResult = soulResultApi.findConclusion(soulReport.getResultId());

        //查询维度
        List<DimensionsVo> list = new ArrayList<>();
        list.add(new DimensionsVo("判断",soulReport.getJudgment().toString()+"%"));
        list.add(new DimensionsVo("外向",soulReport.getOutgoing().toString()+"%"));
        list.add(new DimensionsVo("理性",soulReport.getRationality().toString()+"%"));
        list.add(new DimensionsVo("抽象",soulReport.getAbstract1().toString()+"%"));

        Long userId = UserHolder.getUserId();
        List<SimilarYouVo> similarYouVoList = new ArrayList<>();


        //查询与你相似的人
        List<Long> similarIdList = soulReportApi.findSimilarYou(userId,soulReport.getResultId());
        if (similarIdList != null) {
            for (Long aLong : similarIdList) {
                SimilarYouVo similarYouVo = new SimilarYouVo();
                UserInfo userInfo = userInfoApi.findById(aLong);
                BeanUtils.copyProperties(userInfo,similarYouVo);

                similarYouVoList.add(similarYouVo);
            }
        }
        ReportVo reportVo = new ReportVo();
        reportVo.setConclusion(soulResult.getConclusion());
        reportVo.setCover(soulResult.getCover());
        reportVo.setDimensions(list);
        reportVo.setSimilarYou(similarYouVoList);


        return ResponseEntity.ok(reportVo);
    }
}
